package com.ft.adbix.utils;

import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;

import com.ft.adbix.core.ADBixSdk;
import com.ft.adbix.core.response.Ad;
import com.ft.adbix.core.view.activity.WebViewActivity;

import java.util.List;


public class AdOpener {

    private final Ad ad;
    private final Context context;
    private final AdTrackerReporter reporter;
    private WxLaunchMiniUtil wxLaunchMiniUtil;
    private Handler handler = new Handler();
    private Runnable checkAppOpen = new Runnable() {
        @Override
        public void run() {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.processName.equals(context.getPackageName()) && processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 应用程序在后台运行
                    reporter.reportDeeplink();
                    reporter.reportOpen();
                    break;
                }
            }
        }
    };

    public AdOpener(Context context, Ad ad, AdTrackerReporter reporter) {
        this.ad = ad;
        this.context = context;
        this.reporter = reporter;
    }

    public void openAd() {
        if (ad == null) {
            return;
        }
        //deeplink打开app
        boolean deeplinkSuccess = false;
        if (ad.getDeeplinkType() != 1 && ad.getDeeplinkUrl() != null) {
            reporter.reportTryDeeplink();
            deeplinkSuccess = tryDeeplink(ad.getDeeplinkUrl());
        }
        if (deeplinkSuccess) {
//            handler.postDelayed(checkAppOpen, 10000);
            reporter.reportDeeplink();
            reporter.reportOpen();
            return;
        }

        if (!TextUtils.isEmpty(ad.getWechatId())) {
            try {
                if (WxSupportChecker.checkWxSupport()) {
                    wxLaunchMiniUtil = new WxLaunchMiniUtil();
                    wxLaunchMiniUtil.launchMini(context, ADBixSdk.getInstance().getConfig().getWxAppId(), ad.getWechatId(), ad.getWechatPath());
                    return;
                }
            } catch (Exception e) {

            }
        }
        if (!TextUtils.isEmpty(ad.getLandingPageUrl())) {
            String landingPageUrl = reporter.replace(ad.getLandingPageUrl());
            if (ad.getActionType() == 1) {
                openBrowser();
            }else {
                WebViewActivity.openUrl(context, landingPageUrl, ad.getTitle(), false);
            }
        }

    }

    private void openBrowser(){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(ad.getLandingPageUrl()));
        context.startActivity(intent);
    }

    public void gotoAppStore() {
        Uri uri = Uri.parse("market://details?id=" + ad.getAppPromotion().getAppBundle());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
            reporter.reportAppStoreOpen();
        } catch (ActivityNotFoundException e) {

        }
    }

    private boolean tryDeeplink(String deeplinkUrl) {
        AdLogUtils.i("tryDeepLink===="+deeplinkUrl);
        Uri uri = Uri.parse(deeplinkUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
                return true;
            } else {
                AdLogUtils.i("tryDeepLink==Error==!!");
                return false;
            }
        } catch (Exception e) {
            AdLogUtils.i("tryDeepLink==Error=="+e.getLocalizedMessage());
            return false;
        }
    }

    public void release() {
        handler.removeCallbacks(checkAppOpen);
    }

}
